﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace Translator
{
    public class DictCCProvider : ITranslationProvider
    {
        readonly static Dictionary<string, string> sourceLanguages = new Dictionary<string, string>() { 
            { "Englisch", "EN" },    
            { "Deutsch", "DE" }    
        };

        readonly static Dictionary<string, string> targetLanguages = new Dictionary<string, string>() { 
            { "Deutsch", "DE" },
            { "Englisch", "EN" },
            { "Italienisch", "IT" },
            { "Isländisch", "IS" },
            { "Französisch", "FR" },
            { "Portugiesisch", "PT" },
            { "Ungarisch", "HU" },
            { "Russisch", "RU" },
            { "Niederländisch", "NL" },
            { "Rumänisch", "RO" },
            { "Latein", "LA" },
            { "Schwedisch", "SV" },
            { "Spanisch", "ES" },
            { "Türkisch", "TR" },
            { "Slowakisch", "SK" },
            { "Tschechisch", "CS" },
            { "Bulgarisch", "BG" },
            { "Polnisch", "PL" },
            { "Griechisch", "EL" },
            { "Dänisch", "DA" },
            { "Norwegisch", "NO " },
            { "Bosnisch", "BS" },
            { "Esperanto", "EO" },
            { "Kroatisch", "HR" },
            { "Serbisch", "SR" },
            { "Finnisch", "FI" },
            { "Albanisch", "SQ" } 
        };

        static Regex tableRegEx = new Regex(@"var\s+c(1|2)Arr\s*=\s*new\s+Array\((?<terms>.*?)\);", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        public bool Translate(string word, string sourceLang, string targetLang, out List<Term> terms, out string error)
        {
            terms = new List<Term>();
            error = null;

            string html = GetWebData(string.Format("http://{1}{2}.dict.cc/?s={0}", word, sourceLanguages[sourceLang], targetLanguages[targetLang]));
            if (!string.IsNullOrEmpty(html))
            {
                List<string[]> arrays = new List<string[]>();
                Match match = tableRegEx.Match(html);
                while (match.Success)
                {
                    arrays.Add(match.Groups["terms"].Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
                    match = match.NextMatch();
                }
                if (arrays.Count >= 2)
                {
                    for (int i = 0; i < arrays.Min(e => e.Length); i++)
                    {
                        string w1 = arrays[0][i].Trim(new char[] { '"', ' ' });
                        string w2 = arrays[1][i].Trim(new char[] { '"', ' ' });
                        if (!string.IsNullOrEmpty(w1) && !string.IsNullOrEmpty(w2))
                        {
                            terms.Add(new Term() { Lang1 = w1, Lang2 = w2 });
                        }
                    }
                }
            }
            return true;
        }

        protected static string GetWebData(string url)
        {
            try
            {
                CookieContainer cc = new CookieContainer();
                Cookie c = new Cookie() { Name = "options_str", Value = "sres-pop--limveri-n--nres-20--linkw-n--ttslink-y--hlrows-n--linkp-n--cmenu-n", Expires = DateTime.Now.AddHours(1), Domain = "dict.cc" };
                cc.Add(c);

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;                
                if (request == null) return "";
                request.CookieContainer = cc;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
                request.Timeout = 15000;
                WebResponse response = request.GetResponse();                
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    string str = reader.ReadToEnd();
                    return str.Trim();
                }
            }
            catch
            {
                return "";
            }            
        }

        public string[] SourceLanguages { get { return sourceLanguages.Keys.ToArray(); } }
        public string[] TargetLanguages { get { return targetLanguages.Keys.ToArray(); } }
    }
}
